<template>
    <CrudPage
        :columns="columns"
        :getApi="getBombingApi"
        :createApi="createBombingrApi"
        :updateApi="updateBombingApi"
        :deleteApi="deleteBombingApi"
        :mode="formData"
        v-model:formData="formData"
        :initialFormData="initialFormData"
        :form="form"
        :scroll="true"
        :scrollX="2200"
        :customEditRecord="customEditRecord"
        :beforeModal="
            () => {
                paramsList = [];
                dataList = [];
                headersList = [];
                params = '';
                data = '';
                headers = '';
            }
        "
        :chainResult="
            result => {
                params = JSON.stringify(paramsList.map(({ key, value }) => ({ [key]: value })));
                data = JSON.stringify(dataList.map(({ key, value }) => ({ [key]: value })));
                headers = JSON.stringify(headersList.map(({ key, value }) => ({ [key]: value })));
                console.log({ ...result, params, data, headers });
                return { ...result, params, data, headers };
            }
        "
        :pagination="true"
        :paginationConfig="{
            showTotal(total) {
                return `共${total}条数据`;
            },
        }"
        v-model:filterFormData="filterFormData"
        :initialFilterFormData="initialFilterFormData"
    >
        <template #headButtons>
            <AButton class="operatedBtn" shape="round" @click="handleAllBombing">批量api轰炸</AButton>
            <AButton class="operatedBtn" shape="round" @click="handleAutoBomb">自动化轰炸</AButton>
        </template>
        <template #filter>
            <AFormItem label="标题" name="title">
                <AInput v-model:value="filterFormData.title" placeholder="请输入标题" />
            </AFormItem>
            <AFormItem label="链接" name="url">
                <AInput v-model:value="filterFormData.url" placeholder="请输入链接" />
            </AFormItem>
        </template>
        <template #form>
            <a-collapse v-model:activeKey="activeKey" :accordion="false">
                <a-collapse-panel key="1" header="params">
                    <AButton shape="circle" type="primary" @click="addParamsListItem">
                        <template #icon>
                            <PlusOutlined />
                        </template>
                    </AButton>
                    <ATable :pagination="false" :columns="argumentsColumns" :dataSource="paramsList.map((item, index) => ({ ...item, key: index }))">
                        <template #bodyCell="{ column, index }">
                            <template v-if="column.dataIndex === 'key'">
                                <AInput v-model:value="paramsList[index].key" placeholder="请输入参数名" />
                            </template>
                            <template v-if="column.dataIndex === 'value'">
                                <AInput v-model:value="paramsList[index].value" placeholder="请输入参数值" />
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <AButton danger shape="circle" @click="paramsList.splice(index, 1)">
                                    <template #icon>
                                        <DeleteOutlined />
                                    </template>
                                </AButton>
                            </template>
                        </template>
                    </ATable>
                </a-collapse-panel>
                <a-collapse-panel key="2" header="data">
                    <AButton shape="circle" type="primary" @click="addDataListItem">
                        <template #icon>
                            <PlusOutlined />
                        </template>
                    </AButton>
                    <ATable :pagination="false" :columns="argumentsColumns" :dataSource="dataList.map((item, index) => ({ ...item, key: index }))">
                        <template #bodyCell="{ column, index }">
                            <template v-if="column.dataIndex === 'key'">
                                <AInput v-model:value="dataList[index].key" placeholder="请输入参数名" />
                            </template>
                            <template v-if="column.dataIndex === 'value'">
                                <AInput v-model:value="dataList[index].value" placeholder="请输入参数值" />
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <AButton danger shape="circle" @click="dataList.splice(index, 1)">
                                    <template #icon>
                                        <DeleteOutlined />
                                    </template>
                                </AButton>
                            </template>
                        </template>
                    </ATable>
                </a-collapse-panel>
                <a-collapse-panel key="3" header="headers">
                    <AButton shape="circle" type="primary" @click="addHeaderListItem">
                        <template #icon>
                            <PlusOutlined />
                        </template>
                    </AButton>
                    <ATable :pagination="false" :columns="headersColumns" :dataSource="headersList.map((item, index) => ({ ...item, key: index }))">
                        <template #bodyCell="{ column, index }">
                            <template v-if="column.dataIndex === 'key'">
                                <AInput v-model:value="headersList[index].key" placeholder="请输入请求头名" />
                            </template>
                            <template v-if="column.dataIndex === 'value'">
                                <AInput v-model:value="headersList[index].value" placeholder="请输入请求头值" />
                            </template>
                            <template v-if="column.dataIndex === 'operation'">
                                <AButton danger shape="circle" @click="headersList.splice(index, 1)">
                                    <template #icon>
                                        <DeleteOutlined />
                                    </template>
                                </AButton>
                            </template>
                        </template>
                    </ATable>
                </a-collapse-panel>
            </a-collapse>
        </template>
        <template #operation="{ record }">
            <AButton @click="handleOnecBomb(record)">发送</AButton>
        </template>
    </CrudPage>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from "vue";
import {
    getBombingApi,
    createBombingrApi,
    updateBombingApi,
    deleteBombingApi,
    Bombing,
    startBombingApi,
    bombInBulkApi,
    handleAutoBombApi,
} from "@/api/bombing";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import { filterStatus, filterTime } from "@/filters";
import { httpMessageThrottle } from "@/utils/request";
import lodash from "lodash";
import { message } from "ant-design-vue";
const initialFilterFormData = {
    title: "",
    url: "",
};
export default defineComponent({
    components: { PlusOutlined, DeleteOutlined },
    setup() {
        const initialFormData = {
            title: "",
            url: "",
            method: "GET",
            status: 1,
            params: "",
            data: "",
            headers: "",
        };
        const state = reactive({
            columns: [
                { dataIndex: "_id", title: "ID", width: 17, ellipsis: true, fixed: "left" },
                { dataIndex: "title", title: "标题", width: 13, type: "input", fixed: "left" },
                { dataIndex: "url", title: "链接", width: 20, type: "textarea", ellipsis: true },
                {
                    dataIndex: "method",
                    title: "请求方式",
                    width: 10,
                    type: "select",
                    options: [{ value: "GET" }, { value: "POST" }, { value: "PATCH" }, { value: "DELETE" }, { value: "OPTION" }, { value: "HEAD" }],
                },
                { dataIndex: "data", title: "data", width: 10, ellipsis: true },
                { dataIndex: "params", title: "params", width: 10, ellipsis: true },
                { dataIndex: "headers", title: "headers", width: 10, ellipsis: true },
                {
                    dataIndex: "status",
                    title: "状态",
                    width: 10,
                    type: "select",
                    options: [
                        { value: 0, innerText: "禁用" },
                        { value: 1, innerText: "可用" },
                    ],
                    customRender: filterStatus,
                },
                {
                    dataIndex: "updatedTime",
                    title: "修改时间",
                    width: 14,
                    customRender: filterTime,
                },
                { dataIndex: "operation", title: "操作", width: 16, fixed: "right" },
            ],
            formData: { ...initialFormData },
            argumentsColumns: [
                {
                    dataIndex: "key",
                    title: "参数名",
                },
                {
                    dataIndex: "value",
                    title: "参数值",
                },
                {
                    dataIndex: "operation",
                    title: "操作",
                },
            ],
            headersColumns: [
                {
                    dataIndex: "key",
                    title: "请求头名",
                },
                {
                    dataIndex: "value",
                    title: "请求头值",
                },
                {
                    dataIndex: "operation",
                    title: "操作",
                },
            ],
            paramsList: [],
            dataList: [],
            headersList: [],
            params: "",
            data: "",
            headers: "",
            activeKey: ["1", "2", "3"],
            filterFormData: lodash.cloneDeep(initialFilterFormData),
        });
        const handleOnecBomb = async (record: Bombing) => {
            await startBombingApi({ _id: record._id });
            httpMessageThrottle("已提交", "info");
        };
        const handleAllBombing = () => {
            bombInBulkApi().then(res => {
                if (res.code === 200) {
                    httpMessageThrottle("已开始批量轰炸", "success");
                }
            });
        };
        const handleAutoBomb = () => {
            message.info("已提交");
            handleAutoBombApi().then(res => {
                if (res.code === 200) {
                    message.info(res.message || "轰炸完毕");
                }
            });
        };
        return {
            handleAutoBomb,
            handleAllBombing,
            handleOnecBomb,
            getBombingApi,
            createBombingrApi,
            updateBombingApi,
            deleteBombingApi,
            ...toRefs(state),
            form: state.columns.filter(item => item.type),
            initialFormData,
            console,
            addParamsListItem() {
                (state.paramsList as { key: string; value: string }[]).push({ key: "", value: "" });
            },
            addDataListItem() {
                (state.dataList as { key: string; value: string }[]).push({ key: "", value: "" });
            },
            addHeaderListItem() {
                (state.headersList as { key: string; value: string }[]).push({ key: "", value: "" });
            },
            customEditRecord(record: Bombing) {
                try {
                    state.paramsList = JSON.parse(record.params).map((item: any[]) => {
                        let arr = Object.entries(item)[0];
                        return { key: arr[0], value: arr[1] };
                    });
                } catch {
                    state.paramsList = [];
                }
                try {
                    state.dataList = JSON.parse(record.data).map((item: any[]) => {
                        let arr = Object.entries(item)[0];
                        return { key: arr[0], value: arr[1] };
                    });
                } catch {
                    state.dataList = [];
                }
                try {
                    state.headersList = JSON.parse(record.headers).map((item: any[]) => {
                        let arr = Object.entries(item)[0];
                        return { key: arr[0], value: arr[1] };
                    });
                } catch {
                    state.headersList = [];
                }
                return record;
            },
            initialFilterFormData,
        };
    },
});
</script>

<style scoped lang="scss">
.operatedBtn {
    margin-left: 6px;
}
</style>
